package com.tnovoselec.android.common.io.image;

import java.io.File;
import java.lang.ref.WeakReference;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;

import com.tnovoselec.android.common.util.Md5Util;


public class ImageCachePermanent extends ImageCache {

	@SuppressWarnings("hiding")
	private static final String TAG = ImageCachePermanent.class.getSimpleName();

	private static ImageCachePermanent INSTANCE = null;

	/**
	 * Gets the singleton instance of the ImageCachePermanent.
	 * 
	 * @return The ImageCachePermanent.
	 */
	public synchronized static ImageCachePermanent getInstance() {
		if (ImageCachePermanent.INSTANCE == null) {
			ImageCachePermanent.INSTANCE = new ImageCachePermanent();
		}

		return ImageCachePermanent.INSTANCE;
	}

	@Override
	protected boolean isTimeout(File file) {
		return false;
	}

	public Bitmap loadBitmapFromCache(Context context, String url) {
		Drawable d = loadFromCache(context, url, 0);
		if (d == null) {
			return null;
		}

		return ((BitmapDrawable) d).getBitmap();
	}

	public Drawable loadFromCache(Context context, String url) {
		return loadFromCache(context, url, 0);
	}

	public Drawable loadFromCache(Context context, String url, int defaultResId) {
		String hash = super.getHash(url);
		Drawable d = super.drawableFromCache(url, hash);
		if (d != null) {
			return d;
		}

		File f = new File(context.getCacheDir(), hash);
		if (!f.exists()) {
			d = (defaultResId <= 0) ? null : context.getResources().getDrawable(defaultResId);
		} else {
			d = Drawable.createFromPath(f.getAbsolutePath());

			if (d != null) {
				synchronized (lock) {
					instanceCache.put(hash, new WeakReference<Drawable>(d));
				}
			} else if (defaultResId > 0) {
				d = context.getResources().getDrawable(defaultResId);
			}
		}

		return d;
	}

	public boolean deleteCache(Context context, String url) {
		String hash = Md5Util.md5(url);
		File f = new File(context.getCacheDir(), hash);
		if (!f.exists()) {
			Log.i(ImageCachePermanent.TAG, "File does not exist: " + url);
			return true;
		}

		// TODO Check this synchronization (file deleting)!
		synchronized (lock) {
			instanceCache.remove(hash);
			return f.delete();
		}
	}
}
